package com.uploader.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@Component
public class FileUtils {

    private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);

    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.temp.path}")
    private String tempPath;

    @Value("${file.max-size:10737418240}") // 默认10GB
    private long maxFileSize;

    /**
     * 获取上传目录路径
     */
    public String getUploadDir() {
        return uploadPath != null ? uploadPath : "";
    }
    
    /**
     * 初始化上传目录
     */
    public void initDirs() {
        try {
            Path uploadDir = Paths.get(uploadPath);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
                logger.info("创建上传目录: {}", uploadDir.toAbsolutePath());
            }
            
            Path tempDir = Paths.get(tempPath);
            if (!Files.exists(tempDir)) {
                Files.createDirectories(tempDir);
                logger.info("创建临时目录: {}", tempDir.toAbsolutePath());
            }
        } catch (IOException e) {
            logger.error("初始化目录失败", e);
            throw new RuntimeException("初始化上传目录失败", e);
        }
    }

    /**
     * 保存分片文件
     */
    public void saveChunk(byte[] bytes, String fileHash, int chunkIndex) throws IOException {
        Path chunkDir = Paths.get(tempPath).resolve(fileHash);
        
        // 创建分片目录
        if (!Files.exists(chunkDir)) {
            Files.createDirectories(chunkDir);
        }
        
        Path chunkPath = chunkDir.resolve(String.valueOf(chunkIndex));
        
        // 使用try-with-resources确保资源关闭
        try (FileOutputStream fos = new FileOutputStream(chunkPath.toFile())) {
            fos.write(bytes);
            fos.flush();
        }
        
        logger.debug("保存分片成功: {}, 大小: {} bytes", chunkPath.getFileName(), bytes.length);
    }

    /**
     * 合并分片文件
     */
    public void mergeChunks(String fileHash, String fileName, int totalChunks) throws IOException {
        Path chunkDir = Paths.get(tempPath).resolve(fileHash);
        Path targetPath = Paths.get(uploadPath).resolve(fileName);
        
        // 创建目标文件目录
        if (!Files.exists(targetPath.getParent())) {
            Files.createDirectories(targetPath.getParent());
        }
        
        // 检查所有分片是否都已上传
        validateAllChunksUploaded(chunkDir, totalChunks);
        
        // 使用缓冲流合并文件，提高大文件处理效率
        try (FileOutputStream fos = new FileOutputStream(targetPath.toFile(), true)) {
            byte[] buffer = new byte[8192]; // 8KB缓冲区
            int bytesRead;
            
            for (int i = 0; i < totalChunks; i++) {
                Path chunkPath = chunkDir.resolve(String.valueOf(i));
                
                try (FileInputStream fis = new FileInputStream(chunkPath.toFile())) {
                    while ((bytesRead = fis.read(buffer)) != -1) {
                        fos.write(buffer, 0, bytesRead);
                    }
                }
                
                // 删除已合并的分片
                Files.delete(chunkPath);
                logger.debug("合并并删除分片: {}", i);
            }
        }
        
        // 验证合并后的文件大小
        validateFileSize(targetPath);
        
        // 删除分片目录
        try {
            deleteDirectory(chunkDir);
            logger.info("成功合并文件: {}, 原始分片数: {}", fileName, totalChunks);
        } catch (Exception e) {
            // 即使删除目录失败，文件已经合并成功，只记录日志
            logger.warn("删除分片目录失败: {}", chunkDir, e);
        }
    }

    /**
     * 验证所有分片是否都已上传
     */
    private void validateAllChunksUploaded(Path chunkDir, int totalChunks) throws IOException {
        List<Integer> missingChunks = new ArrayList<>();
        
        for (int i = 0; i < totalChunks; i++) {
            Path chunkPath = chunkDir.resolve(String.valueOf(i));
            if (!Files.exists(chunkPath)) {
                missingChunks.add(i);
            }
        }
        
        if (!missingChunks.isEmpty()) {
            logger.error("缺少分片: {}, 总数: {}", missingChunks, totalChunks);
            throw new IOException("缺少分片文件: " + missingChunks);
        }
    }

    /**
     * 验证文件大小是否超过限制
     */
    private void validateFileSize(Path filePath) throws IOException {
        long fileSize = Files.size(filePath);
        if (fileSize > maxFileSize) {
            // 删除超过大小限制的文件
            Files.deleteIfExists(filePath);
            throw new IOException("文件大小超过限制: " + fileSize + " > " + maxFileSize);
        }
    }

    /**
     * 检查文件是否已存在
     */
    public boolean checkFileExists(String fileName) {
        Path filePath = Paths.get(uploadPath).resolve(fileName);
        boolean exists = Files.exists(filePath);
        logger.debug("检查文件是否存在: {}, 结果: {}", fileName, exists);
        return exists;
    }
    
    /**
     * 删除文件
     */
    public boolean deleteFile(String fileName) {
        try {
            Path filePath = Paths.get(uploadPath).resolve(fileName);
            if (Files.exists(filePath)) {
                Files.delete(filePath);
                logger.info("文件删除成功: {}", fileName);
                return true;
            }
            logger.debug("文件不存在，无需删除: {}", fileName);
            return false;
        } catch (IOException e) {
            logger.error("删除文件失败: {}", fileName, e);
            return false;
        }
    }

    /**
     * 获取已上传的分片索引
     */
    public List<Integer> getUploadedChunks(String fileHash) {
        List<Integer> uploadedChunks = new ArrayList<>();
        Path chunkDir = Paths.get(tempPath).resolve(fileHash);
        
        if (Files.exists(chunkDir) && Files.isDirectory(chunkDir)) {
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(chunkDir)) {
                for (Path entry : stream) {
                    try {
                        String fileName = entry.getFileName().toString();
                        int chunkIndex = Integer.parseInt(fileName);
                        uploadedChunks.add(chunkIndex);
                    } catch (NumberFormatException e) {
                        // 忽略非数字文件名
                        logger.warn("忽略非数字分片文件名: {}", entry.getFileName());
                    }
                }
            } catch (IOException e) {
                logger.error("读取分片目录失败: {}", chunkDir, e);
            }
        }
        
        logger.debug("获取已上传分片: fileHash={}, 数量={}", fileHash, uploadedChunks.size());
        return uploadedChunks;
    }

    /**
     * 递归删除目录
     */
    private void deleteDirectory(Path directory) throws IOException {
        if (!Files.exists(directory)) {
            return;
        }
        
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }
            
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }

    /**
     * 清理过期的临时分片文件
     * 可以在定时任务中调用此方法
     */
    public void cleanupExpiredChunks(long expiryTimeMillis) {
        Path tempDir = Paths.get(tempPath);
        long currentTime = System.currentTimeMillis();
        
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(tempDir)) {
            for (Path chunkDir : stream) {
                if (Files.isDirectory(chunkDir)) {
                    long lastModified = Files.getLastModifiedTime(chunkDir).toMillis();
                    if (currentTime - lastModified > expiryTimeMillis) {
                        logger.info("清理过期分片目录: {}", chunkDir.getFileName());
                        try {
                            deleteDirectory(chunkDir);
                        } catch (IOException e) {
                            logger.error("清理过期分片失败: {}", chunkDir, e);
                        }
                    }
                }
            }
        } catch (IOException e) {
            logger.error("清理过期分片时出错", e);
        }
    }
}